<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="赛事名称" prop="eventName">
        <el-input
            v-model="queryParams.eventName"
            placeholder="请输入赛事名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="赛项名称" prop="competitionName">
        <el-input
            v-model="queryParams.competitionName"
            placeholder="请输入赛项名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="比赛方式" prop="raceType">
        <el-select v-model="queryParams.raceType" placeholder="比赛方式" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_race_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="赛道" prop="track">
        <el-select v-model="queryParams.track" placeholder="赛道" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_track_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column width="55" align="center" label="序号" prop="id"/>
      <el-table-column label="赛事名称" align="center" prop="eventName">
      </el-table-column>
      <el-table-column label="赛项名称" align="center" prop="competitionName" :show-overflow-tooltip="true"/>
      <el-table-column label="赛道" align="center" prop="track">
        <template #default="scope">
          <dict-tag :options="sys_track_type" :value="scope.row.track"/>
        </template>
      </el-table-column>
      <el-table-column label="主办方" align="center" prop="organizers" :show-overflow-tooltip="true"/>
      <el-table-column label="比赛方式" align="center" prop="raceType">
        <template #default="scope">
          <dict-tag :options="sys_race_type" :value="scope.row.raceType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime,"{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">填报人员信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      <el-form ref="postRef" :model="tableList" label-width="100px" :inline="true">
        <el-form-item label="赛事名称:" prop="eventName">
          <el-text>{{ tableList.item.eventName }}</el-text>
        </el-form-item>
        <el-form-item label="赛项名称:" prop="competitionName">
          <el-text>{{ tableList.item.competitionName }}</el-text>
        </el-form-item>
        <el-form-item label="赛道:" prop="track">
          <template #default="scope">
            <dict-tag :options="sys_track_type" :value="tableList.item.track"/>
          </template>
        </el-form-item>
        <el-form-item label="主办方:" prop="organizers">
          <el-text>{{ tableList.item.organizers }}</el-text>
        </el-form-item>
        <el-form-item label="比赛方式:" prop="raceType">
          <template #default="scope">
            <dict-tag :options="sys_race_type" :value="tableList.item.raceType"/>
          </template>
        </el-form-item>
        <el-form-item label="创建时间:" prop="createTime">
          <el-text>{{ tableList.item.createTime,"{y}-{m}-{d}"}}</el-text>
        </el-form-item>
        <el-divider/>
        <el-button type="primary" style="margin-left: 20px;margin-bottom: 10px;float: right" @click="AddItem">
          添加参赛队伍信息
        </el-button>
        <el-table :data="tableList.tableData" style="width: 100%" :rules="rules" border>
          <el-table-column type="index" label="编号" width="70px"/>
          <el-table-column label="选手姓名" width="200px" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.nameStudent`" :rules="rules.nameStudent" align="center">
                <el-input v-model="scope.row.nameStudent" placeholder="选手姓名" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="联系方式" width="200px" prop="numberPhoneStudent" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.numberPhoneStudent`" :rules="rules.numberPhoneStudent">
                <el-input v-model="scope.row.numberPhoneStudent" placeholder="联系方式"
                          style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="身份证号" width="250px" prop="identityCard" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.identityCard`" :rules="rules.identityCard">
                <el-input v-model="scope.row.identityCard" placeholder="身份证号码" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="学号" width="200px" prop="numberId" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.numberId`" :rules="rules.numberId">
                <el-input v-model="scope.row.numberId" placeholder="学号" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="专业" width="200px" prop="major" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.major`" :rules="rules.major">
                <el-input v-model="scope.row.major" placeholder="专业" style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="指导老师姓名" width="200px" prop="nameTeacher" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.nameTeacher`" :rules="rules.nameTeacher">
                <el-input v-model="scope.row.nameTeacher" placeholder="指导老师姓名"
                          style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="指导老师部门" width="200px" prop="deptId" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.deptId`" :rules="rules.deptId" label-width="150px">
                <el-tree-select style="margin-top: 20px" v-model="scope.row.deptId" :data="deptOptions"
                                :props="{ value: 'id', label: 'name', children: 'children' }"
                                :render-after-expand="false"
                                value-key="id" placeholder="指导老师部门" check-strictly/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="指导老师手机号" width="200px" prop="numberPhoneTeacher" align="center">
            <template #default="scope">
              <el-form-item :prop="`tableData.`+scope.$index+`.numberPhoneTeacher`" :rules="rules.numberPhoneTeacher">
                <el-input v-model="scope.row.numberPhoneTeacher" placeholder="指导老师联系方式"
                          style="margin-top: 20px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120" align="center">
            <template #default="scope">
              <el-button link type="danger" size="small" @click="delTeam(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">报 名</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--上传竞赛结果文件-->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".*"
          :headers="upload.headers"
          :action="upload.url + '?module=' + upload.module + '&type='+ upload.type"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="true"
          :drag="true"
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Post">
import {listPost, listDept, addRaceTeam, getRaceTeam, uploadContestRes,delPlayer} from "@/api/contestment/_enlists";

import {getToken} from "@/utils/_auth";

const {proxy} = getCurrentInstance();
const {
  sys_race_type,
  sys_track_type,
  sys_event_value
} = proxy.useDict("sys_race_type", "sys_track_type", "sys_event_value");
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {delEvent} from "@/api/contest/_event";

const postList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
let raceId = ref("");
const tableList = ref({
  item: {
    eventName: '',
    competitionName: '',
    track: '',
    raceType: '',
    createTime: ''
  },
  tableData: [
    {
      deptId: '',
      identityCard: '',
      major: '',
      nameStudent: '',
      nameTeacher: '',
      numberId: '',
      numberPhoneStudent: '',
      numBerPhoneTeacher: '',
    }
  ]
})
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  type: 1,
  module: "xx",
  // 设置上传的请求头部
  headers: {AuthToken: getToken()},
  // 上传的地址
  url: `/api/admin/common/upload`
});
const rules = reactive({
  nameStudent: [{required: true, message: '选手名称不能为空', trigger: 'blur'}],
  identityCard: [
    {
      required: true, message: '身份证号不能为空', trigger: 'blur'
    },
    {
      pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,message:'请输入正确的身份证'
    }
  ],
  major: [{required: true, message: '专业不能为空', trigger: 'blur'}],
  deptId: [{required: true, message: '部门不能为空', trigger: 'change'}],
  nameTeacher: [{required: true, message: '指导老师姓名不能为空', trigger: 'blur'}],
  numberId: [{required: true, message: '学号不能为空', trigger: 'blur'}],
  numberPhoneStudent: [
    {
      required: true, message: '选手联系方式不能为空', trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/, message: '填写正确的联系方式'
    }
  ],
  numberPhoneTeacher: [
    {
      required: true, message: '老师联系方式不能为空', trigger: 'blur'
    },
    {
      pattern: /^1[3-9]\d{9}$/, message: '填写正确的联系方式'
    }
  ],
})
const deptOptions = ref(undefined);
const data = reactive({
  form: {
    id:undefined,
    type: undefined,
    url: undefined,
    name: undefined,
    extensionName: undefined,
    size: undefined,
    fileSize: undefined,
    isSuccess: undefined
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
  },
});

const {form, queryParams} = toRefs(data);

//人员信息填写
function handleUpdate(row) {
  raceId = row.id
  reset()
  listDept(queryParams.value).then(response => {
    deptOptions.value = proxy.handleTree(response.data.result, "id");
  })
  getRaceTeam(row.id).then(response=>{
    tableList.value.item = response.data.result.contest
    if(response.data.result.persons===null){
      AddItem()
    }else{
      tableList.value.tableData = response.data.result.persons
    }
    title.value = '大赛报名'
    open.value = true;
  })


  // reset()
  // AddItem()
  // tableList.value.item = row
  // listDept(queryParams.value).then(response => {
  //   deptOptions.value = proxy.handleTree(response.data.result, "id");
  //   // 数据处理
  // });
  // title.value = '大赛报名'
  // open.value = true;
}

//添加一参赛队伍信息
const AddItem = () => {
  tableList.value.tableData.push({
    deptId: '',
    identityCard: '',
    major: '',
    nameStudent: '',
    nameTeacher: '',
    numberId: '',
    numberPhoneStudent: '',
    numBerPhoneTeacher: '',
  })
}
// 删除参赛人员信息
const delTeam= (row,index) => {
  if (tableList.value.tableData.length <= 1) {
    ElMessage.error("最少需要一个队伍")
  } else {
    console.log(row)
    proxy.$modal.confirm('是否确认删除"' + row.nameStudent+ '"的选手？').then(function() {
      return delPlayer(row.id);
    }).then(() => {
      getList();
      tableList.value.tableData.splice(index, 1)
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }
}

//提交表单
function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      addRaceTeam(tableList.value.tableData, raceId).then(response => {
        ElMessage.success("提交成功")
        open.value = false;
        getList();
      })
    } else {
      ElMessage.error("请确定填写信息是否正确")
    }
  })
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  form.value.url = response.data.url;
  form.value.name = response.data.name;
  form.value.extensionName = response.data.extensionName;
  form.value.size = response.data.size;
  form.value.fileSize = response.data.fileSize;
  form.value.isSuccess = response.data.isSuccess;
  // proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  // getList();
};

/** 提交上传文件 */
function submitFileForm() {
  const v = [form.value]
  uploadContestRes(form.value.id,v).then(response => {
    if (response.data){
      proxy.$modal.msgSuccess("提交成功")
      upload.open = false
    }
  })
};

//表单重置
function reset() {
  proxy.resetForm("postRef");
  tableList.value.tableData.length = 0
}

//取消
function cancel() {
  reset()
  open.value = false
}

/** 查询竞赛列表 */
function getList() {
  loading.value = true;
  listPost(queryParams.value).then(response => {
    postList.value = response.data.result;
    total.value = response.data.total;
    loading.value = false;
  });
}

getList();
</script>
<style>

</style>